﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace KCLIMTrading
{
    class ErrorLog
    {
        private DateTime today = DateTime.Today;
        List<String> temp = new List<String>();

        public ErrorLog()
        {
        }

        public void WriteToLog(String errorMessage)
        {
            String line;
            String path = getPath();

            if (File.Exists(path))
            {
                temp = new List<String>();
                StreamReader reader = new StreamReader(path);
                line = reader.ReadLine();

                while (line != null)
                {
                    temp.Add(line);
                    line = reader.ReadLine();
                }

                foreach (String lineInTxt in temp)
                {
                    System.Diagnostics.Debug.WriteLine("--> " + lineInTxt);
                }

                reader.Close();

                File.Delete(path);
            }

            StreamWriter writer = File.CreateText(path);

            foreach (String error in temp)
            {
                writer.WriteLine(error);
            }

            writer.WriteLine("Time: " + DateTime.Now.ToLongTimeString());
            writer.WriteLine("Error: " + errorMessage);
            writer.WriteLine("=================================================================================================");

            if (writer != null)
                writer.Close();

        }

        private String getPath()
        {
            String pathToSave = AppDomain.CurrentDomain.BaseDirectory + "ErrorLog" + Path.DirectorySeparatorChar + today.ToLongDateString() + ".txt";
            System.Diagnostics.Debug.WriteLine(pathToSave);
            return pathToSave;
        }
    }
}
